﻿using ChineseSchool.BLL;
using ChineseSchool.Models.Hethong;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ChineseSchool.Admin
{
    public partial class QL_Lessons : System.Web.UI.Page
    {
        B_Lessons lessonService = new B_Lessons();
        B_Insert_Update_Delete InsertUpdate = new B_Insert_Update_Delete();
        private List<int> lstIdFileUpload = new List<int>();
        private List<string> lstFileUpload = new List<string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                divAdd.Visible = false;
                divContent.Visible = true;
                BindGrid();
            }
        }

        private void BindDataDropdown()
        {
            var lstLessons = lessonService.GetBy_LessonsParentID(null);

            ddlCourse.Items.Clear();
            ddlCourse.Items.Insert(0, new ListItem("----None----", string.Empty));
            ddlCourse.DataSource = lstLessons;
            ddlCourse.DataTextField = "LessonTitle";
            ddlCourse.DataValueField = "LessonID";
            ddlCourse.DataBind();
        }

        private void BindGrid()
        {
            var lstLesson = lessonService.GetAlls();

            grdLessons.DataSource = lstLesson;
            grdLessons.DataBind();
        }

        private void SaveLesson(int? lessonId)
        {
            var bInsertUpdateDelete = new B_Insert_Update_Delete();

            var lesson = new M_Lessons();
            if (lessonId.HasValue)
                lesson.LessonID = Convert.ToInt32(lessonId);
            if (!string.IsNullOrEmpty(ddlCourse.SelectedValue))
                lesson.LessonParrentID = Convert.ToInt32(ddlCourse.SelectedValue);
            lesson.LessonTitle = txtTitle.Text;
            lesson.LessonSummary = txtSummary.Text;
            lesson.LessonContent = txtContent.Value;
            lesson.PostDate = DateTime.Now;
            if (rbYes.Checked == true)
                lesson.IsLock = true;
            else
                lesson.IsLock = false;

            if (lessonId.HasValue)
            {
                bInsertUpdateDelete.update("Lessons", "LessonID", lesson, lesson.LessonID);
                if (lstIdFileUpload.Count > 0)
                {
                    for (int i = 0; i < lstIdFileUpload.Count; i++)
                    {
                        var homework = (new B_Homework()).GetByPk(lstIdFileUpload[i]);
                        homework.LessonId = lessonId;
                        bInsertUpdateDelete.update("Homework", "HomeworkID", homework, homework.HomeworkId);
                    }
                }
                else
                {
                    if (uploadFile.HasFile)
                    {
                        uploadFile.SaveAs(Server.MapPath("/FilesUpload/" + uploadFile.FileName));
                        var homework = new M_Homework()
                        {
                            LessonId = lessonId,
                            FileAttach = uploadFile.FileName
                        };
                        bInsertUpdateDelete.insert("Homework", "HomeworkID", homework);
                    }
                }
            }
            else
            {
                var newLessonId = bInsertUpdateDelete.InsertReturn("Lessons", "LessonID", lesson);
                if (lstIdFileUpload.Count > 0)
                {
                    for (int i = 0; i < lstIdFileUpload.Count; i++)
                    {
                        var homework = (new B_Homework()).GetByPk(lstIdFileUpload[i]);
                        homework.LessonId = newLessonId;
                        bInsertUpdateDelete.update("Homework", "HomeworkID", homework, homework.HomeworkId);
                    }
                }
                else
                {
                    if (uploadFile.HasFile)
                    {
                        uploadFile.SaveAs(Server.MapPath("/FilesUpload/" + uploadFile.FileName));
                        var homework = new M_Homework()
                        {
                            LessonId = newLessonId,
                            FileAttach = uploadFile.FileName
                        };
                        bInsertUpdateDelete.insert("Homework", "HomeworkID", homework);
                    }
                }
            }
        }

        #region Button Command

        public void BtnNewClicked(object sender, EventArgs e)
        {
            SaveLesson(null);
            divAdd.Visible = false;
            divContent.Visible = true;
            BindGrid();
        }

        public void BtnEditClicked(object sender, EventArgs e)
        {
            SaveLesson(Convert.ToInt32(btnEdit.CommandArgument));
            divAdd.Visible = false;
            divContent.Visible = true;
            BindGrid();
        }

        protected void btnAddnewClicked(object sender, EventArgs e)
        {
            divAdd.Visible = true;
            divContent.Visible = false;
            btnAddnew.Visible = true;
            btnEdit.Visible = false;
            BindDataDropdown();
        }

        protected void btnCancelClicked(object sender, EventArgs e)
        {
            divAdd.Visible = false;
            divContent.Visible = true;
            BindGrid();
        }

        protected void BtnSelectImageClick(object sender, EventArgs e)
        {
            if (uploadAvatar.HasFile)
            {
                var fileName = Session["Username"].ToString() + DateTime.Now.ToString("yyyyMMddHHssfff") + "_" + uploadAvatar.FileName;
                var filePath = Server.MapPath("/FilesUpload/" + fileName);
                uploadAvatar.SaveAs(filePath);
                imgAvatar.ImageUrl = "/FilesUpload/" + fileName;
            }
        }

        #endregion

        #region Grid command

        protected void GrdLessonPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdLessons.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void GrdLessonRowCommand(object sender, GridViewCommandEventArgs e)
        {
            int lessonId = Convert.ToInt32(e.CommandArgument);
            var lesson = lessonService.GetByPK(lessonId);

            if (e.CommandName.Equals("Delete", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    InsertUpdate.delete("Lessons", "LessonID", lesson, lessonId);
                    Response.Write("<script>alert('Đã được xóa!')</script>");
                }
                catch (System.Exception ex)
                {
                    throw new Exception("Đã có lỗi xảy ra! Vui lòng thử lại lần sau!", ex);
                }
                BindGrid();
            }
            if (e.CommandName.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                divAdd.Visible = true;
                divContent.Visible = false;
                btnNew.Visible = false;
                btnEdit.Visible = true;
                BindDataDropdown();

                txtTitle.Text = lesson.LessonTitle;
                txtSummary.Text = lesson.LessonSummary;
                txtContent.Value = lesson.LessonContent;
                if (lesson.IsLock)
                    rbYes.Checked = true;
                else
                    rbNo.Checked = true;

                btnEdit.CommandArgument = lessonId.ToString();
            }
        }

        protected void GrdLessonRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            BindGrid();
        }

        protected void GrdLessonRowEditing(object sender, GridViewEditEventArgs e)
        {
            grdLessons.EditIndex = e.NewEditIndex;
            BindGrid();
        }

        #endregion

        private void BindRptListFile()
        {
            //rptListFileUpload.DataSource = lstFileUpload;
            //rptListFileUpload.DataBind();
        }

        protected void BtnSaveFileClick(object sender, EventArgs e)
        {
            var xxx = lstFileUpload;
            //if (uploadFile.HasFile)
            //{
            //    uploadFile.SaveAs(Server.MapPath("/FilesUpload/" + uploadFile.FileName));
            //    var homework = new M_Homework()
            //    {
            //        FileAttach = uploadFile.FileName
            //    };
            //    int newId = (new B_Insert_Update_Delete()).InsertReturn("Homework", "HomeworkID", homework);
            //    lstIdFileUpload.Add(newId);
            //    lstFileUpload.Add(uploadFile.FileName);
            //    BindGrid();
            //}
        }
    }
}